package com.qiantu.phone.ui.fragment;

import android.Manifest;
import android.animation.ArgbEvaluator;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.android.material.appbar.AppBarLayout;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.base.BaseAdapter;
import com.hjq.http.listener.HttpCallback;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLFloorDBManager;
import com.qiantu.api.db.LLRoomDBManager;
import com.qiantu.api.db.LLSceneDBManager;
import com.qiantu.api.entity.FloorBean;
import com.qiantu.api.entity.RoomBean;
import com.qiantu.api.entity.WeatherInfoBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.app.TitleBarFragment;
import com.qiantu.phone.bean.WeatherIconBean;
import com.qiantu.phone.event.UpdateFavouriteEvent;
import com.qiantu.phone.event.RefreshFloorRoomEvent;
import com.qiantu.phone.event.RefreshHomeDeviceSortSettingEvent;
import com.qiantu.phone.event.RefreshHomeWeatherSettingEvent;
import com.qiantu.phone.scan.ScanCodeActivity;
import com.qiantu.phone.ui.activity.AddDevice1Activity;
import com.qiantu.phone.ui.activity.EditLinkageActivity;
import com.qiantu.phone.ui.activity.EditSceneActivityNew;
import com.qiantu.phone.ui.activity.HomeActivity;
import com.qiantu.phone.ui.activity.MessageCenterActivity;
import com.qiantu.phone.ui.adapter.HomeFragmentPagerAdapter;
import com.qiantu.phone.ui.adapter.RoomOptionAdapter;
import com.qiantu.phone.ui.adapter.HomeFloorAdapter;
import com.qiantu.phone.ui.dialog.AttachListDialog;
import com.qiantu.phone.ui.dialog.OptionDialog;
import com.qiantu.phone.utils.WeatherIconParseUtil;
import com.qiantu.phone.widget.ViewPagerScrollIndicator;
import com.lxj.xpopup.XPopup;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;

/**
 * time   : 2021/12/22
 * desc   : 首页 Fragment
 */
public final class HomeFragment extends TitleBarFragment<HomeActivity> {

    private TextView tvHouseName;
    private TextView tvDistrict;
    private View topBg;
    private View topRoundView;
    private AppBarLayout mAppBar;
    private View tabBarScrollView;
    private View tabBarHolderView;
    private ViewPagerScrollIndicator tabBar;
//    private View tabShadow;
    private ImageView btnTabMore;
    private View btnAdd;
    private View mRoomBottomLine;
    private RecyclerView mRvFloor;
    private ViewPager mViewPager;

//    private FragmentPagerAdapter mPagerAdapter;
    private HomeFragmentPagerAdapter mHomeFragmentPagerAdapter;
    private int dp16;
    private int dp64;
    private int darkColor;
    private Drawable topBgDrawable;
    private int scrollTopColor;
    private int backgroundColor;
    private int statusBarHeight;
    private Drawable rvRoomDrawable;
    private Drawable topRoundDrawable;
    private Drawable tabShadowDrawable;
    private Drawable btnTabMoreDrawable;
//    private Drawable rvFloorDrawable;
    private Drawable viewPagerDrawable;
    private boolean hasFloor;
    private ArgbEvaluator mArgbEvaluator;
    private HomeFloorAdapter mHomeFloorAdapter;
    private FloorBean selectedFloor;
    private int selectedFloorPosition = 0;
    private HashMap<String, String> floorSelectedRoomMap = new HashMap<>();
    private List<RoomBean> selectRooms = new ArrayList<>();
    private List<FloorBean> floors = new ArrayList<>();
    private FloorBean favouriteFloor;
    private FloorBean commonFloor;
    private int tabUnSelectedTextColor;
    private int tabSelectedTextColor;
    private List<String> roomTitles = new ArrayList<>();
    private List<Fragment> fragments = new ArrayList<>();
    private AttachListDialog mAttachListDialog;
    private boolean isFavouriteCommon;
    private String commonlyUsedStr;
    private String commonStr;
    private int firstViewLastFloorRecyclerViewPosition;
    private int firstViewLastFloorRecyclerViewOffset;
    private int currentAppBarVerticalOffset = -1;
    private XXPermissions xxPermissions;
    private int subFragmentTop;
    private long lastGetWeatherTime;
    //获取天气最小间隔5秒
    private int getWeatherInterval = 5000;
    private ViewGroup.LayoutParams topRoundViewLayoutParams;
//    private int topRoundViewHeight;

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.home_fragment;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        topBg = findViewById(R.id.top_bg);
        topRoundView = findViewById(R.id.top_round_view);
        mAppBar = findViewById(R.id.app_bar);
        tvHouseName = findViewById(R.id.tv_house_name);
        tvDistrict = findViewById(R.id.tv_district);
        tabBarScrollView = findViewById(R.id.tab_bar_scroll_view);
        tabBarHolderView = findViewById(R.id.tab_bar_holder_view);
        tabBar = findViewById(R.id.tab_bar);
        btnTabMore = findViewById(R.id.btn_tab_more);
        btnAdd = findViewById(R.id.btn_add);
        mRoomBottomLine = findViewById(R.id.room_bottom_line);
        mRvFloor = findViewById(R.id.rv_floor);
        mViewPager = findViewById(R.id.vp_home_pager);
        setOnClickListener(R.id.btn_message, R.id.btn_add, R.id.btn_tab_more);
        statusBarHeight = ImmersionBar.getStatusBarHeight(getActivity());
        darkColor = AppApplication.getInstance().getThemeColor(R.attr.secondaryColor5);
        topBgDrawable = topBg.getBackground();
        topRoundDrawable = topRoundView.getBackground();
        topRoundViewLayoutParams = topRoundView.getLayoutParams();
        scrollTopColor = AppApplication.getInstance().getThemeColor(R.attr.shapeSolidColor);
        backgroundColor = AppApplication.getInstance().getThemeColor(R.attr.secondaryColor3);
        dp16 = getResources().getDimensionPixelSize(R.dimen.dp_16);
        dp64 = getResources().getDimensionPixelSize(R.dimen.dp_64);
        mArgbEvaluator = new ArgbEvaluator();
        commonlyUsedStr = getString(R.string.commonly_used);
        commonStr = getString(R.string.common);
        mRvFloor.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                //获取可视的第一个view
                View firstView = mRvFloor.getLayoutManager().getChildAt(0);
                if(firstView != null){
                    //获取与该view的左边的偏移量
                    firstViewLastFloorRecyclerViewOffset = firstView.getLeft();
                    //得到该View的数组位置
                    firstViewLastFloorRecyclerViewPosition = mRvFloor.getLayoutManager().getPosition(firstView);
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            }
        });
        mViewPager.addOnPageChangeListener(mOnPageChangeListener);
        mHomeFragmentPagerAdapter = new HomeFragmentPagerAdapter(getChildFragmentManager(), HomeFragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, null);
        mViewPager.setAdapter(mHomeFragmentPagerAdapter);
        updateTopView();
        mAppBar.addOnOffsetChangedListener(mOnOffsetChangedListener);
    }

    private ViewPager.OnPageChangeListener mOnPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            ((HomeActivity) getActivity()).hideLongClickFloatView();
        }

        @Override
        public void onPageSelected(int position) {
            int selectedRoomPosition = position;
            String selectedRoomSerialNo = "";
            if(selectedRoomPosition < selectRooms.size()){
                selectedRoomSerialNo = selectRooms.get(selectedRoomPosition).getRoomSerialNo();
            }else{
                selectedRoomSerialNo = "";
            }
            String floorSerialNo;
            if (selectedFloor != null) {
                floorSerialNo = selectedFloor.getFloorSerialNo();
            } else {
                floorSerialNo = "no_floor";
            }
            floorSelectedRoomMap.put(floorSerialNo, selectedRoomSerialNo);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    private void updateTopView() {
        showTabBar(true);
        if(AppApplication.getInstance().getCurHouseInfo() == null){
            return;
        }
        floors = LLFloorDBManager.getInstance(getContext()).getFloorByHouseSerialNo(AppApplication.getInstance().getCurHouseInfo().getHouseSerialNo());
        hasFloor = floors != null && floors.size() > 0;
        //获取常用
        getFavourite();
        //始终有通用
        commonFloor = new FloorBean();
        commonFloor.setFloorSerialNo("common");
        commonFloor.setFloorName(commonStr);
//        int tabShadowDrawableEndColor;
        if (hasFloor) {
            tabUnSelectedTextColor = AppApplication.getInstance().getThemeColor(R.attr.textColor2);
            tabUnSelectedTextColor = AppApplication.getInstance().getThemeColor(R.attr.textColor2);
            tabSelectedTextColor = AppApplication.getInstance().getThemeColor(R.attr.textColor1);
//            if (currentAppBarVerticalOffset == 0 || currentAppBarVerticalOffset == -1) {
//                tabShadowDrawableEndColor = AppApplication.getInstance().getThemeColor(R.attr.secondaryColor3);
//            }else{
//                tabShadowDrawableEndColor = AppApplication.getInstance().getThemeColor(R.attr.shapeSolidColor);
//            }
            mRvFloor.setVisibility(View.VISIBLE);
            tabBarScrollView.setBackgroundResource(R.drawable.top_round_16dp_secondary_color3);
//            mViewPager.setPadding(0, 0, 0, 0);
            mViewPager.setBackgroundColor(backgroundColor);
            if (mHomeFloorAdapter == null) {
                mHomeFloorAdapter = new HomeFloorAdapter(getContext());
                mHomeFloorAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                        selectedFloorPosition = position;
                        floorScrollToWithOffset(position);
                        selectedFloor = mHomeFloorAdapter.getData().get(position);
                        refreshRoomData();
                        updateRoom();
                    }
                });
            }
            //有楼层，常用和楼层一排
            List<FloorBean> floorTabs = new ArrayList<>();
            if (favouriteFloor != null) {
                floorTabs.add(favouriteFloor);
            }
            for (int i = 0; i < floors.size(); i++) {
                FloorBean floor = floors.get(i);
                floorTabs.add(floor);
            }
            //添加通用
            floorTabs.add(commonFloor);

            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
            linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
            mRvFloor.setAdapter(mHomeFloorAdapter);
            mRvFloor.setLayoutManager(linearLayoutManager);
            mHomeFloorAdapter.setData(floorTabs);
            if (floorTabs != null && floorTabs.size() > 0) {
                //上一次选中的楼层位置
                selectedFloorPosition = floorTabs.size() > selectedFloorPosition ? selectedFloorPosition : floorTabs.size() - 1;
                if (selectedFloor != null) {
                    for (int i = 0; i < floorTabs.size(); i++) {
                        if (floorTabs.get(i).getFloorSerialNo().equals(selectedFloor.getFloorSerialNo())) {
                            //找到一样楼层重置selectedFloorPosition,防止删除位置变了
                            selectedFloorPosition = i;
                            break;
                        }
                    }
                }
                selectedFloor = floorTabs.get(selectedFloorPosition);
                mHomeFloorAdapter.setSelected(selectedFloor);
//                floorScrollToWithOffset(selectedFloorPosition);
                //防止删除下标越界
                firstViewLastFloorRecyclerViewPosition = floorTabs.size() > firstViewLastFloorRecyclerViewPosition ? firstViewLastFloorRecyclerViewPosition : floorTabs.size() - 1;
                linearLayoutManager.scrollToPositionWithOffset(firstViewLastFloorRecyclerViewPosition, firstViewLastFloorRecyclerViewOffset);
                refreshRoomData();
            }
            btnTabMore.setImageDrawable(AppApplication.getInstance().getThemeDrawable(R.attr.icon_home_roomlist_black));
        } else {
            if (currentAppBarVerticalOffset == 0 || currentAppBarVerticalOffset == -1) {
//                tabShadowDrawableEndColor = darkColor;
                tabUnSelectedTextColor = AppApplication.getInstance().getThemeColor(R.attr.alpha99TextColor4);
                tabSelectedTextColor = AppApplication.getInstance().getThemeColor(R.attr.textColor4);
            }else{
//                tabShadowDrawableEndColor = AppApplication.getInstance().getThemeColor(R.attr.shapeSolidColor);
                tabUnSelectedTextColor = AppApplication.getInstance().getThemeColor(R.attr.textColor2);
                tabSelectedTextColor = AppApplication.getInstance().getThemeColor(R.attr.textColor1);
            }
            mRvFloor.setVisibility(View.GONE);
//            tabBarScrollView.setBackground(AppApplication.getInstance().getThemeDrawable(R.attr.home_top_round_16dp_bg));
            tabBarScrollView.setBackgroundColor(0x00000000);
//            mViewPager.setPadding(0, dp16, 0, 0);
            mViewPager.setBackgroundResource(R.drawable.top_round_16dp_secondary_color3);
            if (mHomeFloorAdapter != null) {
                mHomeFloorAdapter.setData(null);
            }
            List<RoomBean> rooms = LLRoomDBManager.getInstance(getContext()).getRoomByHouseSerialNo(AppApplication.getInstance().getCurHouseInfo().getHouseSerialNo());
            selectRooms.clear();
            if(favouriteFloor != null){
                RoomBean favouriteRoom = new RoomBean();
                favouriteRoom.setRoomSerialNo("favourite");
                favouriteRoom.setRoomName(favouriteFloor.getFloorName());
                selectRooms.add(favouriteRoom);
            }
            selectRooms.addAll(rooms);
            RoomBean commonRoom = new RoomBean();
            commonRoom.setRoomSerialNo("common");
            commonRoom.setRoomName(commonStr);
            selectRooms.add(commonRoom);
            btnTabMore.setImageDrawable(AppApplication.getInstance().getThemeDrawable(R.attr.icon_home_roomlist_white));
        }
        tabBar.setUnselectedTextColor(tabUnSelectedTextColor);
        tabBar.setSelectedTexColor(tabSelectedTextColor);
        rvRoomDrawable = tabBarScrollView.getBackground();
//        tabShadowDrawable = tabShadow.getBackground();
//        rvFloorDrawable = mRvFloor.getBackground();
        viewPagerDrawable = mViewPager.getBackground();
        btnTabMoreDrawable = btnTabMore.getDrawable();
        tabBar.setupViewpager(mViewPager);
//        if (tabShadowDrawable instanceof GradientDrawable) {
//            GradientDrawable drawable = (GradientDrawable) tabShadowDrawable;
//            drawable.setColors(new int[]{0x00000000, tabShadowDrawableEndColor});
//        }
        mRoomBottomLine.setVisibility(View.GONE);
        updateRoom();
    }

    private void showTabBar(boolean isSHow){
        if(isSHow){
            tabBar.setVisibility(View.VISIBLE);
//            tabShadow.setVisibility(View.VISIBLE);
            btnTabMore.setVisibility(View.VISIBLE);
            tabBarHolderView.setVisibility(View.GONE);
        }else{
            tabBar.setVisibility(View.GONE);
//            tabShadow.setVisibility(View.GONE);
            btnTabMore.setVisibility(View.GONE);
            tabBarHolderView.setVisibility(View.VISIBLE);
        }
    }

    public void initIndex(){
        selectedFloor = null;
        selectedFloorPosition = 0;
        floorSelectedRoomMap.clear();
    }

    public Drawable getViewPagerBackground(){
        return mViewPager.getBackground();
    }

    private void getFavourite() {
        long favouriteDeviceCount = LLDeviceDBManager.getInstance(getContext()).getFavouriteDeviceCount();
        long favouriteSceneCount = LLSceneDBManager.getInstance(getContext()).getFavouriteSceneCount();
        if (favouriteDeviceCount > 0 || favouriteSceneCount > 0) {
            if (favouriteFloor == null) {
                favouriteFloor = new FloorBean();
                favouriteFloor.setFloorSerialNo("favourite");
                favouriteFloor.setFloorName(commonlyUsedStr);
            }
        } else {
            favouriteFloor = null;
        }
    }

    private void refreshRoomData() {
        selectRooms.clear();
        if ("favourite".equals(selectedFloor.getFloorSerialNo()) || "common".equals(selectedFloor.getFloorSerialNo())) {
            RoomBean room = new RoomBean();
            room.setRoomSerialNo(selectedFloor.getFloorSerialNo());
            room.setRoomName(selectedFloor.getFloorName());
            selectRooms.add(room);
            showTabBar(false);
            isFavouriteCommon = true;
        } else {
            List<RoomBean> rooms = LLRoomDBManager.getInstance(getContext()).getRoomByFloorSerialNo(selectedFloor.getFloorSerialNo());
            selectRooms.addAll(rooms);
            showTabBar(true);
            isFavouriteCommon = false;
        }
    }

    private void updateRoom() {
        List<Fragment> oldFragments = fragments;
        fragments = new ArrayList<>();
        roomTitles.clear();
//        //没有楼层，常用通用和房间一排
//        if (!hasFloor) {
//            if (favouriteFloor != null) {
//                roomTitles.add(favouriteFloor.getFloorName());
//                HomeSubFragment fragment = getHasExistFragment(oldFragments, null, 1);
//                if(fragment == null){
//                    fragment = HomeSubFragment.newInstance(null, 1);
//                }
//                fragments.add(fragment);
//            }
//        }
//        mViewPager.setAdapter(null);
        //点击楼层中的通用和常用会默认生成个通用 常用房间
        for (int i = 0; i < selectRooms.size(); i++) {
            RoomBean room = selectRooms.get(i);
            roomTitles.add(room.getRoomName());
            if ("favourite".equals(room.getRoomSerialNo())) {
                HomeSubFragment fragment = getHasExistFragment(oldFragments, null, 1);
                if(fragment == null){
                    fragment = HomeSubFragment.newInstance(null, 1);
                }
                fragments.add(fragment);
            } else if ("common".equals(room.getRoomSerialNo())) {
                HomeSubFragment fragment = getHasExistFragment(oldFragments, null, 2);
                if(fragment == null){
                    fragment = HomeSubFragment.newInstance(null, 2);
                }
                fragments.add(fragment);
            } else {
                HomeSubFragment fragment = getHasExistFragment(oldFragments, room.getRoomSerialNo(), 0);
                if(fragment == null){
                    fragment = HomeSubFragment.newInstance(room.getRoomSerialNo(), 0);
                }
                fragments.add(fragment);
            }
        }
        if (fragments.size() == 0) {
            fragments.add(new EmptyRoomFragment());
        }
        oldFragments.clear();
        mHomeFragmentPagerAdapter.setFragmentList(fragments);
        mViewPager.removeOnPageChangeListener(mOnPageChangeListener);
        mHomeFragmentPagerAdapter.notifyDataSetChanged();
        tabBar.setTitleList(roomTitles);
        int selectedRoomPosition = 0;
        if (roomTitles.size() > 0) {
            //没有楼层tab包括常用 通用
            if (!hasFloor) {
                String selectedRoomSerialNo = floorSelectedRoomMap.get("no_floor");
                for (int i = 0; i < selectRooms.size(); i++) {
                    if (selectRooms.get(i).getRoomSerialNo() != null && selectRooms.get(i).getRoomSerialNo().equals(selectedRoomSerialNo)) {
                        //找到一样房间重置selectedRoomPosition,防止删除位置变了
                        selectedRoomPosition = i;
                        break;
                    }
                }
            } else {//有楼层,tab不包括常用 通用
                if (selectedFloor != null) {
                    String selectedRoomSerialNo = floorSelectedRoomMap.get(selectedFloor.getFloorSerialNo());
                    for (int i = 0; i < selectRooms.size(); i++) {
                        //有楼层selectRooms里可能是常用 通用
                        if (selectRooms.get(i).getRoomSerialNo() != null && selectRooms.get(i).getRoomSerialNo().equals(selectedRoomSerialNo)) {
                            //找到一样房间重置selectedRoomPosition,防止删除位置变了
                            selectedRoomPosition = i;
                            break;
                        }
                    }
                }
            }
        }
        mViewPager.addOnPageChangeListener(mOnPageChangeListener);
        tabBar.selectTab(selectedRoomPosition);
        if (roomTitles.size() <= 6) {
            btnTabMore.setVisibility(View.GONE);
        } else {
            btnTabMore.setVisibility(View.VISIBLE);
        }
    }

    private HomeSubFragment getHasExistFragment(List<Fragment> fragments, String roomSerialNo, int type){
        for(Fragment fragment : fragments){
            if(fragment instanceof HomeSubFragment){
                HomeSubFragment homeSubFragment = (HomeSubFragment) fragment;
                if((roomSerialNo == null && homeSubFragment.getType() == type)
                        || (roomSerialNo != null && roomSerialNo.equals(homeSubFragment.getRoomSerialNo()))){
                    return homeSubFragment;
                }
            }
        }
        return null;
    }

    public HomeSubFragment getCurrentFragment(){
        if(fragments == null || fragments.size() == 0){
            return null;
        }
        for(int i=0;i<fragments.size(); i++){
            Fragment f = fragments.get(i);
            if(i == mViewPager.getCurrentItem() && f instanceof HomeSubFragment){
                return (HomeSubFragment) f;
            }
        }
        return null;
    }

    private AppBarLayout.OnOffsetChangedListener mOnOffsetChangedListener = new AppBarLayout.OnOffsetChangedListener() {
        @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
            Log.i("luzx", "currentAppBarVerticalOffset:" + currentAppBarVerticalOffset + "==verticalOffset:" + verticalOffset);
            if (currentAppBarVerticalOffset == verticalOffset) {
                return;
            }
            float totalScrollRange = appBarLayout.getTotalScrollRange();
            currentAppBarVerticalOffset = verticalOffset;
            ((HomeActivity) getActivity()).hideLongClickFloatView();
            Log.i("lzx", "verticalOffset:" + verticalOffset);
//            int rvFloorDrawableColor = 0;
            int rvRoomDrawableColor = 0;
//            int roomBottomLineColor = 0;
            float cornerRadius = 0;
//            int tabShadowDrawableEndColor = 0;
            int alpha = 0;
            if (verticalOffset == 0) {
                alpha = 255;
                topBgDrawable.setAlpha(alpha);
//                rvFloorDrawableColor = darkColor;
                if (hasFloor) {
//                    mViewPager.setPadding(0, 0, 0, 0);
                    subFragmentTop = 0;
                    updateSubFragmentTop();
                    rvRoomDrawableColor = backgroundColor;
//                    roomBottomLineColor = backgroundColor;
//                    tabShadowDrawableEndColor = AppApplication.getInstance().getThemeColor(R.attr.secondaryColor3);
                    btnTabMoreDrawable = AppApplication.getInstance().getThemeDrawable(R.attr.icon_home_roomlist_black);
                } else {
                    tabUnSelectedTextColor = AppApplication.getInstance().getThemeColor(R.attr.alpha99TextColor4);
                    tabSelectedTextColor = AppApplication.getInstance().getThemeColor(R.attr.textColor4);
                    rvRoomDrawableColor = 0x00000000;
//                    roomBottomLineColor = darkColor;
//                    tabShadowDrawableEndColor = darkColor;
                    btnTabMoreDrawable = AppApplication.getInstance().getThemeDrawable(R.attr.icon_home_roomlist_white);
                }
                mRoomBottomLine.setVisibility(View.GONE);
//                if (!isFavouriteCommon) {
//                    mRoomBottomLine.setVisibility(View.VISIBLE);
//                    mRoomBottomLine.setBackgroundColor(roomBottomLineColor);
//                }
                tabBarScrollView.setPadding(0, 0, 0, 0);
                topRoundViewLayoutParams.height = dp64;
                cornerRadius = dp16;
                if(!isHidden()){
                    getAttachActivity().getStatusBarConfig().statusBarDarkFont(AppApplication.getInstance().getThemeBoolean(R.attr.statusBarChangeIsDarkFont)).init();
                }
            } else if (Math.abs(verticalOffset) >= totalScrollRange) {
                alpha = 0;
                topBgDrawable.setAlpha(alpha);
//                rvFloorDrawableColor = 0x00000000;
                if(hasFloor){
                    subFragmentTop = dp16;
                    updateSubFragmentTop();
                }else{
                    tabUnSelectedTextColor = AppApplication.getInstance().getThemeColor(R.attr.textColor2);
                    tabSelectedTextColor = AppApplication.getInstance().getThemeColor(R.attr.textColor1);
                }
                rvRoomDrawableColor = scrollTopColor;
//                tabShadowDrawableEndColor = AppApplication.getInstance().getThemeColor(R.attr.shapeSolidColor);
                btnTabMoreDrawable = AppApplication.getInstance().getThemeDrawable(R.attr.icon_home_roomlist_black);
                if (!isFavouriteCommon) {
                    mRoomBottomLine.setVisibility(View.VISIBLE);
//                    mRoomBottomLine.setBackgroundColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor7));
                }
                tabBarScrollView.setPadding(0, statusBarHeight, 0, 0);
                topRoundViewLayoutParams.height = dp64 + statusBarHeight;
                cornerRadius = 0;
                if(!isHidden()) {
                    getAttachActivity().getStatusBarConfig().statusBarDarkFont(AppApplication.getInstance().getThemeBoolean(R.attr.statusBarIsDarkFont)).init();
                }
            } else {
                float fraction = Math.abs(verticalOffset) / totalScrollRange;
                alpha = (int) ((1 - fraction) * 255);
                topBgDrawable.setAlpha(alpha);
//                rvFloorDrawableColor = Color.argb(alpha, Color.red(darkColor), Color.green(darkColor), Color.blue(darkColor));
                if (hasFloor) {
                    rvRoomDrawableColor = (int) (mArgbEvaluator.evaluate(fraction, backgroundColor, scrollTopColor));
                    subFragmentTop = (int) (dp16 * fraction);
                    updateSubFragmentTop();
//                    Log.i("lzx", "viewPagerPaddingTop:" + viewPagerPaddingTop);
//                    if (mViewPager.getPaddingTop() != viewPagerPaddingTop) {
//                        mViewPager.setPadding(0, viewPagerPaddingTop, 0, 0);
//                    }修改成更新topSceneView
//                    Fragment currentFragment = fragments.get(mViewPager.getCurrentItem());
                } else {
                    tabUnSelectedTextColor = (int) (mArgbEvaluator.evaluate(fraction, AppApplication.getInstance().getThemeColor(R.attr.alpha99TextColor4), AppApplication.getInstance().getThemeColor(R.attr.textColor2)));
                    tabSelectedTextColor = (int) (mArgbEvaluator.evaluate(fraction, AppApplication.getInstance().getThemeColor(R.attr.textColor4), AppApplication.getInstance().getThemeColor(R.attr.textColor1)));
//                    rvRoomDrawableColor = Color.argb(alpha, Color.red(darkColor), Color.green(darkColor), Color.blue(darkColor));
                }
//                tabShadowDrawableEndColor = 0x00000000;
                mRoomBottomLine.setVisibility(View.GONE);
                cornerRadius = (1 - fraction) * dp16;
                int tabBarPaddingTop = (int) (statusBarHeight * fraction);
                Log.i("lzx", "tabBarPaddingTop:" + tabBarPaddingTop);
                if (tabBarScrollView.getPaddingTop() != tabBarPaddingTop) {
                    tabBarScrollView.setPadding(0, tabBarPaddingTop, 0, 0);
                    topRoundViewLayoutParams.height = dp64 + tabBarPaddingTop;
                }
            }
            topBg.setBackground(topBgDrawable);
            topRoundDrawable.setAlpha(alpha);
            if(topRoundDrawable instanceof GradientDrawable){
                GradientDrawable gradientDrawable = (GradientDrawable) topRoundDrawable;
                gradientDrawable.setCornerRadii(new float[]{
                        cornerRadius,//radiusTopLeftX
                        cornerRadius,//radiusTopLeftY
                        cornerRadius,//radiusTopRightX
                        cornerRadius,//radiusTopRightY
                        0,//radiusBottomRightX
                        0,//radiusBottomRightY
                        0,//radiusBottomLeftX
                        0//radiusBottomLeftY
                });
            }
            topRoundView.setTranslationY(currentAppBarVerticalOffset);
            btnTabMore.setImageDrawable(btnTabMoreDrawable);
//            if (tabShadowDrawable instanceof GradientDrawable) {
//                GradientDrawable drawable = (GradientDrawable) tabShadowDrawable;
//                drawable.setColors(new int[]{0x00000000, tabShadowDrawableEndColor});
//            }
            //渐变更新房间背景
            GradientDrawable rvRoomGradientDrawable = null;
            if (rvRoomDrawable instanceof GradientDrawable) {
                rvRoomGradientDrawable = (GradientDrawable) rvRoomDrawable;
                //渐变更新房间背景的圆角
                rvRoomGradientDrawable.setCornerRadii(new float[]{
                        cornerRadius,//radiusTopLeftX
                        cornerRadius,//radiusTopLeftY
                        cornerRadius,//radiusTopRightX
                        cornerRadius,//radiusTopRightY
                        0,//radiusBottomRightX
                        0,//radiusBottomRightY
                        0,//radiusBottomLeftX
                        0//radiusBottomLeftY
                });
            }
            if (hasFloor) {
                //有楼层时，不是通用、常用时房间栏需要渐变
                if (!isFavouriteCommon && rvRoomGradientDrawable != null) {
                    rvRoomGradientDrawable.setColor(rvRoomDrawableColor);
                }
            } else {
                tabBar.changeTextColor(tabUnSelectedTextColor, tabSelectedTextColor);
                //viewPager背景的第一层颜色跟着房屋的背景渐变 第二层圆角渐变直角
//                if (viewPagerDrawable instanceof LayerDrawable) {
//                    LayerDrawable layerDrawable = (LayerDrawable) viewPagerDrawable;
////                    gradientDrawable1 = (GradientDrawable) layerDrawable.getDrawable(0);
//                    gradientDrawable2 = (GradientDrawable) layerDrawable.getDrawable(1);
////                    gradientDrawable1.setColor(rvFloorDrawableColor);
//                    gradientDrawable2.setCornerRadii(new float[]{
//                            cornerRadius,//radiusTopLeftX
//                            cornerRadius,//radiusTopLeftY
//                            cornerRadius,//radiusTopRightX
//                            cornerRadius,//radiusTopRightY
//                            0,//radiusBottomRightX
//                            0,//radiusBottomRightY
//                            0,//radiusBottomLeftX
//                            0//radiusBottomLeftY
//                    });
//                }
                if (viewPagerDrawable instanceof GradientDrawable) {
                    GradientDrawable gradientDrawable = (GradientDrawable) viewPagerDrawable;
                    gradientDrawable.setCornerRadii(new float[]{
                            cornerRadius,//radiusTopLeftX
                            cornerRadius,//radiusTopLeftY
                            cornerRadius,//radiusTopRightX
                            cornerRadius,//radiusTopRightY
                            0,//radiusBottomRightX
                            0,//radiusBottomRightY
                            0,//radiusBottomLeftX
                            0//radiusBottomLeftY
                    });
                }
            }
        }
    };

    private void updateSubFragmentTop(){
        if(isFavouriteCommon){
            return;
        }
        for(Fragment fragment : fragments){
            if (fragment != null && fragment instanceof HomeSubFragment && fragment.isAdded() && !fragment.isHidden()) {
                ((HomeSubFragment) fragment).updateTop(subFragmentTop);
            }
        }
    }

    public int getSubFragmentTop(){
        return subFragmentTop;
    }

    public boolean hasFloor() {
        return hasFloor;
    }

    private void floorScrollToWithOffset(int position) {
        if (mRvFloor != null && mHomeFloorAdapter != null) {
            LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRvFloor.getLayoutManager();
            int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition();
            int newPosition;
            if (firstVisibleItemPosition >= position - 1) {
                newPosition = position - 1;
                newPosition = newPosition < 0 ? 0 : newPosition;
            } else {
                newPosition = position + 1;
                newPosition = newPosition > mHomeFloorAdapter.getItemCount() - 1 ? mHomeFloorAdapter.getItemCount() - 1 : newPosition;
            }
            mRvFloor.smoothScrollToPosition(newPosition);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshFloorRoomEvent(RefreshFloorRoomEvent event) {
        updateTopView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAddFavouriteEvent(UpdateFavouriteEvent event) {
        if(event.type == UpdateFavouriteEvent.TYPE_ADD && favouriteFloor == null){
            updateTopView();
        }else if(event.type == UpdateFavouriteEvent.TYPE_CANCEL && favouriteFloor != null){
            //重新获取下常用,没有就更新
            getFavourite();
            if(favouriteFloor == null){
                updateTopView();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshHomeWeatherSettingEvent(RefreshHomeWeatherSettingEvent event) {
        Log.i("lzxlzxlzx", "onRefreshHomeWeatherSettingEvent");
        updateHeaderInfo();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshHomeDeviceSortSettingEvent(RefreshHomeDeviceSortSettingEvent event) {
    }

    /**
     * HomeActivity getAppSetting获取成功后，根据是否显示天气设置再获取天气
     */
    private void updateHeaderInfo(){
        tvHouseName.setText(AppApplication.getInstance().getCurHouseInfo().getName());
//        if (AppApplication.getInstance().mSettingBean != null && AppApplication.getInstance().mSettingBean.getSetting().getInterfaceCustomization().isEnvironmentalData()) {
//            setWeatherInfo();
//        } else {
//            if (ivWeather != null) {
//                ivWeather.setVisibility(View.GONE);
//                tvDistrict.setVisibility(View.GONE);
//                tvTemperature.setVisibility(View.GONE);
//            }
//        }
    }

    @Override
    protected void initData() {
        updateHeaderInfo();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_message:
                startActivity(MessageCenterActivity.class);
                break;
            case R.id.btn_tab_more:
                showAttachListDialog();
                break;
            case R.id.btn_add:
                showOptionDialog(btnAdd);
                break;
        }
    }

    private void showAttachListDialog() {
        if (mAttachListDialog == null) {
            mAttachListDialog = new AttachListDialog(getContext());
            mAttachListDialog.setDialogClickListener(new AttachListDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {

                }
            });
            RoomOptionAdapter attachOptionAdapter = new RoomOptionAdapter(getContext());
            attachOptionAdapter.setData(selectRooms);
            attachOptionAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                    tabBar.selectTab(position);
                    mAttachListDialog.dismiss();
                }
            });
            mAttachListDialog.setAdapter(attachOptionAdapter);
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .atView(btnTabMore)
                    .offsetY(-btnTabMore.getHeight())
                    .asCustom(mAttachListDialog);
        }
        RoomOptionAdapter roomOptionAdapter = (RoomOptionAdapter) mAttachListDialog.getAdapter();
        roomOptionAdapter.checkSelected(selectRooms.get(tabBar.getCurrentItem()));
        mAttachListDialog.scrollTo(tabBar.getCurrentItem());
        mAttachListDialog.show();
    }

    private OptionDialog optionDialog;

    private void showOptionDialog(View atView) {
        if (optionDialog == null) {
            List<OptionDialog.Option> options = new ArrayList<>();
            options.add(new OptionDialog.Option(R.attr.icon_home_scancode, "扫一扫"));
            options.add(new OptionDialog.Option(R.attr.icon_home_adddevice, "添加设备"));
            options.add(new OptionDialog.Option(R.attr.icon_home_addscenes, "添加场景"));
            options.add(new OptionDialog.Option(R.attr.icon_home_addlinkage, "添加联动"));
            optionDialog = new OptionDialog(getContext())
                    .setOptions(options).setListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                            optionDialog.dismiss();
                            Intent intent = null;
                            switch (position) {
                                case 0:
                                    if (xxPermissions == null) {
                                        xxPermissions = XXPermissions.with(getActivity());
                                    }
                                    xxPermissions.permission(Manifest.permission.CAMERA)
                                            .request(new OnPermissionCallback() {
                                                @Override
                                                public void onGranted(List<String> permissions, boolean all) {
                                                    if (all) {
                                                        Intent intent = new Intent(getContext(), ScanCodeActivity.class);
                                                        startActivity(intent);
                                                    }
                                                }

                                                @Override
                                                public void onDenied(List<String> permissions, boolean never) {
                                                    ToastUtils.show(R.string.common_permission_fail_1);
                                                }

                                            });
                                    break;
                                case 1:
                                    intent = new Intent(getContext(), AddDevice1Activity.class);
                                    startActivity(intent);
                                    break;
                                case 2:
                                    startActivity(EditSceneActivityNew.class);
                                    break;
                                case 3:
                                    startActivity(EditLinkageActivity.class);
                                    break;
                            }
                        }
                    });
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .atView(atView)
                    .offsetX(getResources().getDimensionPixelSize(R.dimen.dp_10))
                    .asCustom(optionDialog);
        }
        optionDialog.show();
    }

//    private void setWeatherInfo() {
//        if (ivWeather != null) {
//            if(System.currentTimeMillis() - lastGetWeatherTime > getWeatherInterval) {
//                LLHttpManager.getWeather(this,
//                        AppApplication.getInstance().getCurHouseInfo().getLongitude(),
//                        AppApplication.getInstance().getCurHouseInfo().getLatitude(),
//                        new HttpCallback<HttpData<WeatherInfoBean>>(null) {
//                            @Override
//                            public void onStart(Call call) {
//                                super.onStart(call);
//                            }
//
//                            @Override
//                            public void onSucceed(HttpData<WeatherInfoBean> result) {
//                                super.onSucceed(result);
//                                tvDistrict.setText(AppApplication.getInstance().getCurHouseInfo().getDistrict());
//                                ivWeather.setVisibility(View.VISIBLE);
//                                tvDistrict.setVisibility(View.VISIBLE);
//                                tvTemperature.setVisibility(View.VISIBLE);
//                                if (result.getData() != null) {
//                                    WeatherIconBean weatherIcon = WeatherIconParseUtil.getIcon(getActivity(), result.getData().getWeatherCode());
//                                    if (weatherIcon != null){
//                                        ivWeather.setImageResource(getResources().getIdentifier(weatherIcon.getImage(), "mipmap", AppApplication.getInstance().getPackageName()));
//                                    }
//                                    if (!TextUtils.isEmpty(result.getData().getTemperatureC())) {
//                                        tvTemperature.setText(result.getData().getTemperatureC() + "°c");
//                                    }
//                                }
//                            }
//
//                            @Override
//                            public void onFail(Exception e) {
//                                super.onFail(e);
//                            }
//
//                            @Override
//                            public void onEnd(Call call) {
//                                super.onEnd(call);
//                            }
//                        });
//            }
//            lastGetWeatherTime = System.currentTimeMillis();
//        }
//    }

    @Override
    public boolean isStatusBarEnabled() {
        // 使用沉浸式状态栏
        return !super.isStatusBarEnabled();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isHidden()) {
            if (currentAppBarVerticalOffset == 0 || currentAppBarVerticalOffset == -1) {
                getStatusBarConfig().statusBarDarkFont(AppApplication.getInstance().getThemeBoolean(R.attr.statusBarChangeIsDarkFont)).init();
            } else {
                getStatusBarConfig().statusBarDarkFont(AppApplication.getInstance().getThemeBoolean(R.attr.statusBarIsDarkFont)).init();
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!isHidden()) {
            if (currentAppBarVerticalOffset == 0 || currentAppBarVerticalOffset == -1) {
                getAttachActivity().getStatusBarConfig().statusBarDarkFont(AppApplication.getInstance().getThemeBoolean(R.attr.statusBarChangeIsDarkFont)).init();
            } else {
                getAttachActivity().getStatusBarConfig().statusBarDarkFont(AppApplication.getInstance().getThemeBoolean(R.attr.statusBarIsDarkFont)).init();
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        mViewPager.setAdapter(null);
    }
}